package springinpractice.ch4.r4_5.model;

import java.util.Arrays;
import java.util.Set;

import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;

/*
 * Author       :       Willie Wheeler and John Wheeler
 * Book         :       'Spring In Practice' [Book written by Willie Wheeler and John Wheeler]
 */

@SuppressWarnings("serial")
public class UserDetailsAdapter extends org.springframework.security.userdetails.User {
	private final Long id;
	
	public UserDetailsAdapter(User user) {
		super(user.getUsername(), user.getPassword(), user.isEnabled(),
				true, true, true, toAuthorities(user.getRoles()));
		this.id = user.getId();
	}
	
	private static GrantedAuthority[] toAuthorities(Set<String> roles) {
		GrantedAuthority[] auths = new GrantedAuthority[roles.size()];
		int i = 0;
		for (String role : roles) {
			auths[i++] = new GrantedAuthorityImpl(role);
		}
		Arrays.sort(auths);
		return auths;
	}
	
	public Long getId() {
		return id;
	}
}
